package com.leap.filter;


import com.auth0.jwt.interfaces.DecodedJWT;
import com.leap.mini.MiniAuthenticationToken;
import com.leap.service.AdminService;
import com.leap.utils.JwtUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Collection;
import java.util.List;

@Component
public class JwtAuthorizeFilter extends OncePerRequestFilter {

    @Autowired
    private AdminService adminService;

    @Resource
    JwtUtils utils;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        String authorization = request.getHeader("Authorization");
        DecodedJWT jwt = utils.resolveJwt(authorization);
        if (jwt != null){
            String openid = utils.toOpenid(jwt);
            String username = utils.toUsername(jwt);
            if (openid != null){
                MiniAuthenticationToken authentication =
                        new MiniAuthenticationToken(openid, null,null);
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }else if (username != null){
                UserDetails admin = adminService.loadUserByUsername(username);
                UsernamePasswordAuthenticationToken authentication =
                        new UsernamePasswordAuthenticationToken(username, admin.getPassword(),admin.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }else {
                throw new UsernameNotFoundException("Username or password is incorrect");
            }

            //TODO:需要时 可往Session中丢用户信息
            //request.setAttribute("openid", openid);
        }
        filterChain.doFilter(request,response);
    }
}
